<template>
	<view class="container" :style="[containHeight]">
		<view class="search-content">
			<view class="search-item">
				<text class="search-label">考试名称：</text>
				<u--input placeholder="请输入考试名称" border="surround" v-model="searchParams.name"></u--input>
			</view>
			<view class="search-item">
				<text class="search-label">状态：</text>
				<u-picker :show="isStatus" :columns="options.results" v-model="searchParams.status"
					@confirm="isStatusConfirm" @cancel="isStatus=false" keyName="label" class="form-picker"></u-picker>
				<view class="select-border-width" @click="isStatus=true">
					<text v-if="!searchParams.status">请选择状态</text>
					<text v-if="searchParams.status" class="selectedTxt">
						<text>{{searchParams.status}}</text>
					</text>
				</view>
			</view>
			<view class="btn-group">
				<u-button text="查询" type="primary" :loading="btnSearch" loadingText="查询中" class="search-btn"
					@click="toSearch"></u-button>
			</view>
		</view>
		<view class="content">
			<view class="delItem layout-start">
				<u-button text="创建试卷规则" color="linear-gradient(to right, #7774ff, #017ffd,#01b1fd)"
					@click="newcrowd()"></u-button>
			</view>
			<view v-if="basicTrainList.length==0">
				<u-empty mode="list" icon="../../static/listEmpty.png"></u-empty>
			</view>
			<u-swipe-action v-for="(item,index) in basicTrainList" :key="index" autoClose v-else>
				<u-swipe-action-item :options="optionscrowd" @click="swipeItem(item,$event)">
					<view class="historicalAchievements_item u-border-bottom">
						<text class="bold greyTxt">考试名称：</text>
						<text class="bold">{{item.name}}</text>
						<view class="layout-between">
							<view class="includePeopleTxt">
								<text class="bold greyTxt">考试时长:</text>
								<text>{{item.duration}}分钟 </text>
							</view>
							<view class="includePeopleTxt">
								<text class="bold greyTxt">及格线:</text>
								<text class="bule">{{item.passScore}}分 </text>
							</view>
						</view>
						<u-row>
							<u-col span="4">
								<view class="includePeopleTxt layout-start">
									<text class="bold greyTxt">状态:</text>
									<u-tag plain :text="item.status == 0 ? '正常' : '禁用'" size="mini"></u-tag>
								</view>
							</u-col>
							<u-col span="4">
								<view class="includePeopleTxt layout-start">
									<text class="bold greyTxt">是否重复:</text>
									<u-tag plain :text="item.canRedo == 0 ? '是' : '否'" size="mini"></u-tag>
								</view>
							</u-col>
							<u-col span="4">
								<view class="includePeopleTxt layout-start">
									<text class="bold greyTxt">是否限时:</text>
									<u-tag plain :text="item.timeLimited == 0 ? '是' : '否'" size="mini"></u-tag>
								</view>
							</u-col>
						</u-row>
						<view class="includePeopleTxt">
							<text class="bold greyTxt">开始时间:</text>
							<text>{{item.startTime}} </text>
						</view>
						<view class="includePeopleTxt">
							<text class="bold greyTxt">结束时间:</text>
							<text>{{item.endTime}} </text>
						</view>
					</view>
				</u-swipe-action-item>
			</u-swipe-action>
		</view>
		<u-popup :show="isNewEdit" mode="center" @close="closeNewEdit" @open="getHistoryData">
			<view class="popupContent">
				<view class="popupTitle">{{formTitle == 0 ? '创建试卷规则' : '编辑试卷规则'}}</view>
				<u--form labelPosition="left" labelWidth="95" :model="formPopup" ref="uForm">
					<u-form-item label="考试名称" prop="name" required>
						<u--input placeholder="请输入考试名称" border="surround" v-model="formPopup.name"></u--input>
					</u-form-item>
					<u-form-item label="题库" prop="questionBankId">
						<zxz-uni-data-select :localdata="options.bankName" placeholder="请选择题库"
							v-model="formPopup.questionBankId" dataKey="key" dataValue="value"
							@change="isResultsConfirm">
						</zxz-uni-data-select>
					</u-form-item>
					<u-form-item label="单选题个数" prop="singleChoiceNum">
						<u-number-box v-model="formPopup.singleChoiceNum"></u-number-box>
					</u-form-item>
					<u-form-item label="单选题得分" prop="singleChoiceScore">
						<u-number-box v-model="formPopup.singleChoiceScore"></u-number-box>
					</u-form-item>
					<u-form-item label="多选题个数" prop="multiChoiceNum">
						<u-number-box v-model="formPopup.multiChoiceNum"></u-number-box>
					</u-form-item>
					<u-form-item label="多选题得分" prop="multiChoiceScore">
						<u-number-box v-model="formPopup.multiChoiceScore"></u-number-box>
					</u-form-item>
					<u-form-item label="判断题个数" prop="judgeChoiceNum">
						<u-number-box v-model="formPopup.judgeChoiceNum"></u-number-box>
					</u-form-item>
					<u-form-item label="判断题得分" prop="judgeChoiceScore">
						<u-number-box v-model="formPopup.judgeChoiceScore"></u-number-box>
					</u-form-item>
					<u-form-item label="考试时长(分钟)" prop="duration">
						<u-number-box v-model="formPopup.duration"></u-number-box>
					</u-form-item>
					<u-form-item label="及格线" prop="passScore">
						<u-number-box v-model="formPopup.passScore"></u-number-box>
					</u-form-item>

					<u-form-item label="考试人群" prop="examCrowdId">
						<zxz-uni-data-select :multiple="true" :localdata="options.examCrowd.list" placeholder="请选择考试人群"
							v-model="formPopup.examCrowdId" dataKey="key" dataValue="value" collapseTags
							@change="changeDept">
						</zxz-uni-data-select>
					</u-form-item>
					<!-- 考试人群定考试人员 -->
					<u-form-item label="考试人员" prop="examCrowdIds">
						<u--textarea v-model="formPopup.examCrowdIds" disabled></u--textarea>
					</u-form-item>
					<u-form-item label="时间" prop="">
						<view class="dateBorder">
							<uni-datetime-picker v-model="rangeDate" type="datetimerange" :border="false" />
						</view>
					</u-form-item>
					<!-- 0代表否，1代表是 -->
					<u-form-item prop="learningScoreRecorded" label="是否记录学分">
						<u-switch v-model="formPopup.learningScoreRecorded" :activeValue="1"
							:inactiveValue="0"></u-switch>
					</u-form-item>
					<u-form-item label="可获得学分数" prop="learningScore">
						<u-number-box v-model="formPopup.learningScore"></u-number-box>
					</u-form-item>
					<u-form-item prop="learningTimeRecorded" label="是否记录学时">
						<u-switch v-model="formPopup.learningTimeRecorded" :activeValue="1"
							:inactiveValue="0"></u-switch>
					</u-form-item>
					<u-form-item label="可获得学时数" prop="learningTime">
						<u-number-box v-model="formPopup.learningTime"></u-number-box>
					</u-form-item>
					<u-form-item label="是否限时" prop="timeLimited">
						<u-switch v-model="formPopup.timeLimited" :activeValue="0" :inactiveValue="1"></u-switch>
					</u-form-item>
					<u-form-item label="状态" prop="status">
						<u-switch v-model="formPopup.status" :activeValue="1" :inactiveValue="0" activeColor="#ff4949"
							activeText="禁用" inactiveText="正常"></u-switch>
					</u-form-item>
					<u-form-item label="是否可重复考" prop="canRedo">
						<!-- 0代表是，1代表否 -->
						<u-switch v-model="formPopup.canRedo" :activeValue="0" :inactiveValue="1"></u-switch>
					</u-form-item>
					<u-form-item label="可重复考次数" prop="redoNum">
						<zxz-uni-data-select :localdata="options.redoList" placeholder="请选择可重复考次数"
							v-model="formPopup.redoNum" dataKey="key" dataValue="value" @change="isredoNumConfirm">
						</zxz-uni-data-select>
					</u-form-item>
					<u-form-item label="考试介绍" prop="examIntroduce" class="mB80">
						<u--textarea v-model="formPopup.examIntroduce" placeholder="请输入考试介绍"></u--textarea>
					</u-form-item>
				</u--form>
				<view class="btn-group absolutePosition">
					<u-button text="取消" class="reset-btn" @click="cancelCrowd('uForm')"></u-button>
					<u-button text="确认" type="primary" class="search-btn" @click="confirmcrowd('uForm')"></u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		examMain,
		selectBankName,
		selectExamCrowd,
		examSelect,
		examAdd,
		examUpdate,
		viewExam
	} from "../../utils/api.js"
	export default {
		data() {
			return {
				fullHeight: true,
				basicTrainList: [],
				searchParams: {
					examCategoryId: "",
					name: "",
					status: "正常", //状态， 默认0代表正常，1代表禁用
				},
				btnSearch: false,
				optionscrowd: [{
					text: '编辑',
					style: {
						backgroundColor: '#3c9cff'
					}
				}],
				isNewEdit: false,
				formTitle: 0, // 0-创建/1-编辑				
				formPopup: {
					name: "", //试卷名称
					questionBankId: null, //题库id
					singleChoiceNum: 0, //单选题个数
					singleChoiceScore: 0, //每个单选题得分
					multiChoiceNum: 0, //多选题个数
					multiChoiceScore: 0, //每个多选题得分
					judgeChoiceNum: 0, //判断选择题个数
					judgeChoiceScore: 0, //每个判断选择题得分
					duration: 0, //考试时长（分钟）
					passScore: 0, //及格线
					examCrowdId: [], //参加考试的人群id列表
					examCrowdIds: "", //参加考试的人员列表
					startTime: "", //考试开始时间
					endTime: "", //考试结束时间
					learningTimeRecorded: 0, //是否记录学时 默认0代表不记录，1代表记录
					learningTime: 0, //考试通过后可获得学时数
					learningScoreRecorded: 0, //是否记录学分
					learningScore: 0, //考试通过后可获得学分数
					timeLimited: 0, //是否限时 默认0代表限时，1代表不限时
					canRedo: 0, //是否可重复考 0代表允许，1代表不允许
					status: 0, // 状态 0-正常 1-禁用
					redoNum: null, //重复次数
					examIntroduce: "", //考试介绍
				},
				rangeDate: [],
				options: {
					examCrowd: {
						list: [],
						checked: false,
					},
					results: [
						[{
								label: "正常",
								value: '0',
							},
							{
								label: "禁用",
								value: '1',
							},

						]
					],
					redoList: [{
							key: "1次",
							value: 1,
						},
						{
							key: "2次",
							value: 2,
						}, {
							key: "3次",
							value: 3,
						},
						{
							key: "4次",
							value: 4,
						}, {
							key: "5次",
							value: 5,
						},
						{
							key: "不限次数",
							value: -1,
						},

					],
					bankName: [],
				},
				//仅用于像后端传递数据
				paramsValue: {
					examCategoryId: '',
					status: '', //默认0代表正常，1代表禁用
					name: '',
				},
				isStatus: false,
			}
		},
		onLoad() {
			this.userId = uni.getStorageSync('userinfo').id
			this.getbasicTrainList()
			this.getOptions()
		},
		computed: {
			containHeight() {
				return this.fullHeight ? {
					/*#ifdef MP-WEIXIN*/
					// 微信小程序特有代码
					height: '100vh',
					/*#endif*/
					/*#ifndef MP-WEIXIN*/
					height: 'calc(100vh - 44px)'
					/*#endif*/
				} : {
					height: '100%'
				}
			},
		},
		onReachBottom() {
			if (this.fullHeight) {
				this.fullHeight = false
			}
		},
		methods: {
			getbasicTrainList(isdel) {
				examMain().then(s => {
					if (s.code === 20000) {
						this.basicTrainList = s.data
						// if (isdel == 'ture') {
						// 	//删除操作
						// 	this.basicTrainList = s.data
						// } else {
						// 	this.basicTrainList = this.basicTrainList.concat(s.data)
						// }
						// this.total = s.data.total
						// if (this.total < this.pageSize) {
						// 	this.statusLoading = 'nomore'
						// }
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
			},
			toSearch() {
				this.btnSearch = true
				this.basicTrainList = []
				this.paramsValue.status = this.searchParams.status == '禁用' ? 1 : 0
				this.paramsValue.name = this.searchParams.name
				//过滤空的参数
				const params = Object.keys(this.paramsValue).filter((key) => this.paramsValue[key] !== null && this
					.paramsValue[key] !== '' && this.paramsValue[key] !== undefined).reduce((acc, key) => ({
					...acc,
					[key]: this.paramsValue[key]
				}), {})
				// console.log("const params", params);
				examSelect(params).then(s => {
					// console.log("查询s", s);
					if (s.code === 20000) {
						//搜索结果反映到视图
						this.btnSearch = false
						this.basicTrainList = s.data
					} else {
						uni.showToast({
							title: s.message,
							icon: 'none'
						})
					}
				})
			},
			swipeItem(item, e) {
				// console.log("swipeItem e", e);
				console.log("item", item);
				if (e.index == 0) {
					//编辑
					this.isNewEdit = true
					this.formTitle = 1
					viewExam({
						id: item.id,
					}).then(s => {
						if (s.code === 20000) {
							this.formPopup = s.data
							this.rangeDate = []
							this.rangeDate[0] = this.formPopup.startTime
							this.rangeDate[1] = this.formPopup.endTime
							console.log("this.formPopup", this.formPopup);
							// console.log("this.rangeDate",this.rangeDate);
							this.changeDept()
						} else {
							uni.showToast({
								title: s.message,
								icon: "none"
							})
						}
					})
				} else {

				}
			},
			newcrowd() {
				this.isNewEdit = true
				this.formTitle = 0;
			},
			confirmcrowd() {
				this.isNewEdit = false
				this.formPopup.startTime = this.rangeDate[0]
				this.formPopup.endTime = this.rangeDate[1]
				let data = JSON.parse(JSON.stringify(this.formPopup));
				this.setHistoryData(data);
				if (this.formTitle == 0) {
					//创建
					examAdd(data).then(s => {
						if (s.code === 20000) {
							uni.showToast({
								title: '创建成功',
								icon: 'success'
							})
							this.getbasicTrainList()
						} else {
							uni.showToast({
								title: s.message,
								icon: 'error'
							})
						}
					})
				} else if (this.formTitle == 1) {
					//编辑
					examUpdate(data).then(s => {
						if (s.code === 20000) {
							uni.showToast({
								title: '更新成功',
								icon: 'success'
							})
						} else {
							uni.showToast({
								title: s.message,
								icon: 'none'
							})
						}
					})
				}
			},
			cancelCrowd(formName) {
				this.isNewEdit = false
				this.$refs[formName].resetFields()
				this.rangeDate = []
			},
			// 获取下拉列表
			getOptions() {
				selectBankName().then(s => {
					if (s.code === 20000) {
						this.options.bankName = s.data.map(item => ({
							key: item.bank_name,
							value: item.id,
						}));
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
				selectExamCrowd().then(s => {
					if (s.code === 20000) {
						this.options.examCrowd.list = s.data.map(item => ({
							key: item.crowd_name,
							value: item.id,
							includePeoples: item.include_peoples
						}));
					} else {
						uni.showToast({
							title: s.message,
							icon: "none"
						})
					}
				})
			},
			changeDept() {
				let arr1 = this.formPopup.examCrowdId;
				let arr2 = this.options.examCrowd.list;
				// console.log(arr1, arr2);
				if (arr1) {
					let equ = arr2.filter((item) => arr1.some((ele) => ele === item.value));
					// console.log("equ", equ);
					let str = "";
					equ.forEach((e) => {
						if (!str) str = str.concat(e.includePeoples);
						else str = str.concat(",", e.includePeoples);
					});
					this.formPopup.examCrowdIds = str;
				}

			},
			isResultsConfirm(val) {
				// console.log("val",val);
			},

			isStatusConfirm(val) {
				// console.log("val",val);
				this.isStatus = false
				this.searchParams.status = val.value[0].label
			},
			closeNewEdit() {
				this.formPopup = {}
				this.isNewEdit = false
			},
			isredoNumConfirm(val) {
				// console.log("val 1",val);				
			},
			// 存入提交的题目数量、分值
			setHistoryData(data) {
				let history = {
					singleChoiceNum: 0, //单选题个数
					singleChoiceScore: 0, //每个单选题得分
					multiChoiceNum: 0, //多选题个数
					multiChoiceScore: 0, //每个多选题得分
					judgeChoiceNum: 0, //判断选择题个数
					judgeChoiceScore: 0, //每个判断选择题得分
					duration: 0, //考试时长（分钟）
					passScore: 0, //及格线
				};
				for (let k in history) {
					history[k] = data[k];
				}
				// console.log("history", history);
				uni.setStorageSync('jqCommonExamHistory', JSON.stringify(history))
			},
			// 获取上次提交的题目数量、分值
			getHistoryData() {
				if (uni.getStorageSync('jqCommonExamHistory')) {
					let history = JSON.parse(uni.getStorageSync('jqCommonExamHistory'));
					// console.log("history", history);
					for (let k in history) {
						this.formPopup[k] = history[k];
					}
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background: linear-gradient(#5191FF 5%, #6AA2FF 8%, #BDD7FE 15%, #F6FAFF 100%);
		padding: 30rpx 30rpx;
		width: 100%;
		position: relative;
		box-sizing: border-box;

		.content {
			background: #ffffff;
			margin-top: 30rpx;
			padding: 30rpx 32rpx;
			box-sizing: border-box;
			border-radius: 15rpx;
			opacity: 0.9;
			width: 100%;
			position: relative;
		}
	}


	.historicalAchievements_item {
		background: #ffffff;
		box-sizing: border-box;
		padding: 30rpx;

		// border-radius: 20rpx;
		// box-shadow: 4px 4px 10px #888888;
		.line {
			height: 1rpx;
			background: #737375;
			width: 100%;
			margin: 30rpx 0rpx;
		}

	}


	.search-content {
		box-sizing: border-box;
		padding: 15rpx;
		width: 100%;
		position: relative;
		background: #ffffff;
		border-radius: 15rpx;

		.search-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			width: 100%;
			margin-top: 10rpx;
			font-size: 30rpx;
			box-sizing: border-box;
			padding: 10rpx 20rpx;

		}

		.search-label {
			max-width: 300rpx;
			overflow: hidden;
			// text-overflow: ellipsis;
			white-space: nowrap;
			font-size: 30rpx;
		}


	}

	.btn-group {
		display: flex;
		margin-top: 60rpx;
		width: 100%;
		position: relative;
		justify-content: space-between;

		.search-btn {
			width: 40%;
			border-radius: 100rpx;
			background: linear-gradient(to right, #7774ff, #017ffd, #01b1fd);
			color: #fff;
		}

		.reset-btn {
			width: 40%;
			border-radius: 100rpx;
		}

	}

	.bold {
		font-weight: 700;
		white-space: nowrap;
	}

	.delItem {
		width: 30%;
		padding-top: 20rpx;
		box-sizing: border-box;
		position: relative;
		margin-bottom: 20rpx;
	}

	.popupContent {
		margin-top: 20rpx;
		height: 1200rpx; // 固定高度
		overflow-y: scroll; // 超出滚动
		overscroll-behavior: none; // 禁止滚动溢出
	}


	/deep/.u-swipe-action-item__right {
		position: absolute;
		top: 1px;
		bottom: 1px;
		right: 1px;
	}

	/deep/.u-popup__content {
		width: 90%;
		position: relative;
		padding: 40rpx;
		box-sizing: border-box;
		overflow: auto;
	}

	.popupTitle {
		font-weight: 900;
		white-space: nowrap;
		line-height: 1.6;
		text-align: center;
		position: -webkit-sticky;
		position: sticky;
		top: 0;
		z-index: 2;
		background: #ffffff;

	}

	.absolutePosition {
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #ffffff;
		margin: 0rpx 0rpx 20rpx 0rpx;
		box-sizing: border-box;
		padding-top: 20rpx;
	}

	.mB80 {
		margin-bottom: 80rpx;
	}

	.includePeopleTxt {
		// width: 90%;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		line-height: 1.8;
	}

	.select-border-width {
		width: 77%;
		height: 38px;
		line-height: 38px;
		border: 0.5px solid #dadbde;
		color: #B1B1B1;
		box-sizing: border-box;
		padding: 0rpx 25rpx;
		font-size: 16px;

	}

	.selectedTxt {
		color: rgb(48, 49, 51);
	}

	.dateBorder {
		width: 100%;
		height: 38px;
		border: 1px solid #dadbde;
		// border-radius: 50rpx;
		box-sizing: border-box;
		padding: 0rpx 25rpx;
		font-size: 16px;
		// z-index: 1;
	}

	.bule {
		color: #3888FF;
		font-size: 32rpx;
	}

	.greyTxt {
		color: #9A9EA1;
	}

	.form-picker {
		/deep/.u-popup__content {
			width: 100%;
			padding: 0;
		}
	}
</style>